<%@ page language="java" import="com.alibaba.fastjson.JSONObject" pageEncoding="UTF-8" %>
<%@ page import="com.cloudstore.eccom.gyxy.utils.MessageUtil" %>
<%@ page import="org.springframework.web.multipart.MultipartFile" %>
<%@ page import="java.io.*" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.URL" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.UUID" %>
<%--获取传阅数量--%>
<%
    // 获取access_token
    String tokenUrl = "http://58.193.84.162:82/api/rest/token/getAccessToken";
    String param = "appkey=u7WydyxyKIjR4ybAab&appsecret=1cd2038c27fc48fe83e12d39a9075e0e";
    String result = MessageUtil.getToken(tokenUrl, param);
    JSONObject resultJson = JSONObject.parseObject(result);
    String accessToken = resultJson.getString("access_token");
    out.println("accessToken="+accessToken);
    //发送纯文本消息
    String sendUrl = "http://58.193.84.162:82/api/rest/message/sendMessage";
    try {
        Map<String, String> requestText = new HashMap<String, String>();
        requestText.put("accesstoken", URLEncoder.encode(accessToken, "UTF-8"));
        requestText.put("xxlx", URLEncoder.encode("sms", "UTF-8"));
        requestText.put("userid", URLEncoder.encode("133005", "UTF-8"));
        requestText.put("sender", URLEncoder.encode("测试人员", "UTF-8"));
        requestText.put("msgtype", "4");
        requestText.put("title", URLEncoder.encode("OA流程测试1", "UTF-8"));
        requestText.put("templatecode", URLEncoder.encode("DBTZ001", "UTF-8"));
        requestText.put("templateparam", URLEncoder.encode("{'sxmc':'费用报销流程','sqr':'何高英'}", "UTF-8"));
        requestText.put("url", URLEncoder.encode("url", "UTF-8"));
        requestText.put("sfrz", "0");
        out.println("requestText="+requestText);
        result =  sendRequest(sendUrl, requestText, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    out.println("result="+result);
%>
<%!

    private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");
    private final static String PREFIX = "--";
    private final static String LINE_END = "\r\n";

    public static String getToken(String url, String par) {
        String result = "";
        HttpURLConnection httpConn = null;
        DataOutputStream out = null;
        BufferedReader in = null;
        try {
            java.net.URL urlObject = new URL(url);
            httpConn = (HttpURLConnection) urlObject.openConnection();
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpConn.setRequestMethod("POST");
            httpConn.setReadTimeout(30000);
            httpConn.setConnectTimeout(30000);
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);

            out = new DataOutputStream(httpConn.getOutputStream());
            if (par != null) {
                out.write(par.getBytes("UTF-8"));
            }
            out.flush();
            out.close();

            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result = result + inputLine;
            }
            in.close();
            httpConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;

    }

    public static String sendRequest(String requestUrl, Map<String, String> requestText, Map<String, MultipartFile> requestFile) {
        HttpURLConnection conn = null;
        InputStream input = null;
        OutputStream os = null;
        BufferedReader br = null;
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            conn.connect();
            os = new DataOutputStream(conn.getOutputStream());
            writeParams(requestText, os);
            //writeFile(requestFile, os);
            String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
            os.write(endTarget.getBytes());
            os.flush();
            if (conn.getResponseCode() == 200) {
                input = conn.getInputStream();
            } else {
                input = conn.getErrorStream();
            }

            br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            System.out.println("######" + buffer.toString());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                    conn = null;
                }

                if (os != null) {
                    os.close();
                    os = null;
                }

                if (br != null) {
                    br.close();
                    br = null;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer.toString();
    }

    private static void writeParams(Map<String, String> requestText, OutputStream os) {
        try {
            String msg = "请求文本参数部分:\n";
            if (requestText == null || requestText.isEmpty()) {
                msg += "空";
            } else {
                StringBuilder requestParams = new StringBuilder();
                Iterator<Map.Entry<String, String>> it = requestText.entrySet()
                        .iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    requestParams.append(PREFIX).append(BOUNDARY)
                            .append(LINE_END);
                    requestParams
                            .append("Content-Disposition: form-data; name=\"")
                            .append(entry.getKey()).append("\"")
                            .append(LINE_END);
                    requestParams.append(
                            "Content-Type: text/plain; charset=utf-8").append(
                            LINE_END);
                    requestParams.append("Content-Transfer-Encoding: 8bit")
                            .append(LINE_END);
                    requestParams.append(LINE_END);
                    requestParams.append(entry.getValue());
                    requestParams.append(LINE_END);
                }
                os.write(requestParams.toString().getBytes());
                os.flush();
                msg += requestParams.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

%>